package com.example.zhihuijiaju;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.accessibilityservice.AccessibilityService;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.MacAddress;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkRequest;
import android.net.NetworkSpecifier;
import android.net.Uri;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiNetworkSpecifier;
import android.net.wifi.WifiNetworkSuggestion;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.PatternMatcher;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.transform.Result;
import javax.xml.transform.sax.TemplatesHandler;

import static android.view.View.INVISIBLE;


public class Add extends AppCompatActivity {

    private static final String TAG = "Add";
    WifiManager wifiManager;
    View Loading;
    ProgressDialog dialog;//弹窗

    public static final  int requestCode = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add);
        Loading = findViewById(R.id.progressBar);
        //动态权限
        String[] PERMS_INITIAL = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.CHANGE_NETWORK_STATE, Manifest.permission.WRITE_SETTINGS};
        requestPermissions(PERMS_INITIAL, 127);

        Log.i(TAG, "已打印");

        //设置用户wifi
        SetUserWIFI();
    }

    //设置用户wifi
    private void SetUserWIFI() {
        //显示等待
        Loading.setVisibility(View.VISIBLE);
        wifiManager = (WifiManager)
                this.getSystemService(Context.WIFI_SERVICE);
        BroadcastReceiver wifiScanReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                boolean success = intent.getBooleanExtra(
                        WifiManager.EXTRA_RESULTS_UPDATED, false);

                Loading.setVisibility(View.GONE);

                if (success) {
                    scanSuccess();
                } else {
                    // scan failure handling
                    scanFailure();
                }
            }
        };

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        this.registerReceiver(wifiScanReceiver, intentFilter);

        boolean success = wifiManager.startScan();
        if (!success) {
            // scan failure handling
            scanFailure();
        }
    }

    //获取wifi成功
    private void scanSuccess() {
        List<ScanResult> results = wifiManager.getScanResults();
        List<Map<String, Object>> listitem = new ArrayList<Map<String, Object>>();
        for (int in = 0; in < results.size(); in++) {
            //  Log.i(TAG, results.get(in).toString());
            Map<String, Object> showitem = new HashMap<String, Object>();
            showitem.put("SSID", results.get(in).SSID);
            showitem.put("BSSID", results.get(in).BSSID);
            listitem.add(showitem);
        }
        SimpleAdapter myAdapter = new SimpleAdapter(
                getApplicationContext(),
                listitem,
                R.layout.wifi_item,
                new String[]{"SSID"},
                new int[]{R.id.ssid}
        );
        ListView listView = (ListView) findViewById(R.id.list_item);
        listView.setAdapter(myAdapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //传输用户wifi名字与密码
                // Object listItem = listView.getItemAtPosition(position);
                //  Log.i(TAG, String.valueOf(position));
                // Log.i(TAG, listitem.get(position).toString());
                String ssid = listitem.get(position).get("SSID").toString();
                String bssid = listitem.get(position).get("BSSID").toString();
                Log.i(TAG, ssid + "  " + bssid);

                final String[] password = new String[1];
                final EditText et = new EditText(Add.this);
                new AlertDialog.Builder(Add.this).setTitle("请输入\"" + ssid + "\"的密码")
                        //  .setIcon(android.R.drawable.sym_def_app_icon)
                        .setView(et)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                                hintKeyBoard();
                                dialog = new ProgressDialog(Add.this);
                                dialog.setCancelable(false);
                                dialog.setTitle("正在玩命加载中...");
                                //设置一下进度条的样式
                                dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                                //设置进度条的最大值
                                dialog.setMax(100);
                                dialog.show();

                                //按下确定键后的事件
                                Log.i(TAG, "传输");
                                password[0] = et.getText().toString();
                                Log.i(TAG, password[0]);
                                String data = "{\"ssid\":\"" + ssid + "\",\"password\":\"" + password[0] + "\"}";
                                Log.i(TAG, data);
                                new UdpClientThread(mHandler,
                                        "192.168.4.1",
                                        8266,
                                        data
                                ).start();
                            }
                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        hintKeyBoard();
                    }
                }).show();
            }
        });

        //... use new scan results ...
    }

    /**
     * Handler
     */
    private Handler mHandler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0: {
                    String content = (String) msg.obj;
                    Log.i(TAG,content);
                    //mTxtContent.setText(content);
                    JSONObject jsonObject = JSONObject.parseObject(content);
                    int code = jsonObject.getShort("code");
                    switch (code) {
                        case -1:
                            dialog.dismiss();
                          //  Toast.makeText(Add.this,"失败",Toast.LENGTH_SHORT).show();
                            break;
                        case 0:
                            dialog.setProgress(50);
                            break;
                        case 1:
                            dialog.setProgress(80);
                            break;
                        case 2:
                            ok_connect(content);
                            break;
                        default:
                            dialog.dismiss();
                            Toast.makeText(Add.this,"未知错误",Toast.LENGTH_SHORT).show();
                    }
                    Log.i(TAG, content);
                    break;
                }
            }
        }
    };


    //配网成功
    private void ok_connect(String connect)
    {
        JSONObject jsonObject = JSONObject.parseObject(connect);
        dialog.dismiss();
        Toast.makeText(Add.this,"连接成功",Toast.LENGTH_SHORT).show();
        //MODE_WORLD_WRITEABLE
        String devices_data;
        try{
            devices_data = FileOperations.file_read(Add.this,"devices");
            JSONObject jst=  JSONObject.parseObject(devices_data);
            JSONArray jsonArray = new JSONArray(jst.getJSONArray("data"));

            JSONObject jst1=  JSONObject.parseObject("{\"CLIENT_ID\":\""+jsonObject.get("CLIENT_ID")+"\",\"deviceId\":\""+jsonObject.get("deviceId")+"\"}");
            jsonArray.add(jst1);
            JSONObject jst2 = new JSONObject();

            jst2.put("data",jsonArray);

            FileOperations.file_write(Add.this,"devices",jst2.toString());

        } catch (Exception e) {
            e.printStackTrace();
            FileOperations.file_write(Add.this,"devices","{\"data\":[{\"CLIENT_ID\":\""+jsonObject.get("CLIENT_ID")+"\",\"deviceId\":\""+jsonObject.get("deviceId")+"\"}]}");
        }
//        Intent intent = new Intent();
//        intent.setClass(Add.this, MainActivity.class);
//        startActivity(intent);

        Intent resultIntent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putString("device","{\"CLIENT_ID\":\""+jsonObject.get("CLIENT_ID")+"\",\"deviceId\":\""+jsonObject.get("deviceId")+"\"}");
        resultIntent.putExtras(bundle);
        this.setResult(RESULT_OK,resultIntent);
        this.finish();

    }

    /**
     * 将获取到的int型ip转成string类型
     */
    private String getIpString(int ipAddress) {
        return (ipAddress & 0xFF) + "." + ((ipAddress >> 8) & 0xFF) + "."
                + ((ipAddress >> 16) & 0xFF) + "." + (ipAddress >> 24 & 0xFF);
    }

    //获取wifi失败
    private void scanFailure() {
        // handle failure: new scan did NOT succeed
        // consider using old scan results: these are the OLD results!
        List<ScanResult> results = wifiManager.getScanResults();
        //... potentially use older scan results ...
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.fanhui:
                Add.this.finish();
                overridePendingTransition(R.anim.bottomout_enter, R.anim.bottomout_exit);
                break;
        }
    }

    //复写onKeyDown事件
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Add.this.finish();
            overridePendingTransition(R.anim.bottomout_enter, R.anim.bottomout_exit);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }



    //关闭键盘
    public void hintKeyBoard() {
        //拿到InputMethodManager
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        //如果window上view获取焦点 && view不为空
        if (imm.isActive() && getCurrentFocus() != null) {
            //拿到view的token 不为空
            if (getCurrentFocus().getWindowToken() != null) {
                //表示软键盘窗口总是隐藏，除非开始时以SHOW_FORCED显示。
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }
}
